package cn.jee.jsp;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/checkInDbServlet")
public class CheckInDbServlet extends HttpServlet {
  String driver = "org.hsqldb.jdbc.JDBCDriver";
  String url = "jdbc:hsqldb:hsql://localhost/";
  String user = "sa";
  String pass = "";

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    boolean flag = false;
    //数据库查询
    try {
      Class.forName(driver);
      String sql="select * from user where username=? and password=?";
      try (
              Connection con = DriverManager.getConnection(url, this.user, this.pass);
              PreparedStatement pstmt=con.prepareStatement(sql);
      ) {
        pstmt.setString(1,username);
        pstmt.setString(2,password);
        try(ResultSet rs=pstmt.executeQuery();){
          flag=rs.next();
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    HttpSession session=req.getSession();
    if(flag){
      session.setAttribute("login_user",username);
      resp.sendRedirect(req.getContextPath()+"/login_suc.jsp");
    }else{
      resp.sendRedirect(req.getContextPath()+"/login_fail.jsp");
    }
  }
}
